<?php
/**
 * 作者：Savage www.520internet.com
 */

//	[调用检测] 检测其他程序是否能调用该文件
    if (!defined('Mi18n')) {
        exit('Access Denied');
    }

class Mi18n
{
    public $dbObj;
    private $tableName = '';
    // 错误数组信息
    public $errorArr = array();
    // 错误信息对照表
    public $message = array(
      '10100' => '未设置数据库表名',
      '10101' => '查询信息失败',
      '10102' => '查询列表失败',
      '10103' => '搜索信息失败',
      '10104' => '增加信息失败',
      '10105' => '更新信息失败',
      '10106' => '删除信息失败',
      '10107' => '替换信息失败',
    );

    /**
     * 构造函数
     **/
    public function __construct()
    {
        $this->init();
    }

    /**
     * 连接数据库
     * @return null;
     **/
    public function init()
    {
        try {
            $this->dbObj = MSQLite::getInstance();
        } catch (exception $e) {
            throw new exception($errorArr);
        }
    }

    /**
     * 设置数据库表名
     * @return null;
     **/
    public function setTableName($tableName)
    {
        $this->tableName = $tableName;
    }

    /**
     * 更新数据
     * @param string $field, 需要编辑的数据字段名;
     * @param string $value, 需要编辑的数据字段名;
     * @param array $dataAarr, 需要编辑的数据;
     * @return boolean;
     * @example obj->updateByField('id', '1', array('title' => 'title', 'content' => 'content'));
     **/
    public function updateByField($field, $value, $dataArr, $where='')
    {
        if ($this->tableName == ''){
          $this->errorArr = array('code'=>10100, 'message'=>$this->message[10100]);
          return fasle;
        }
        // 插入数据库
        $result = $this->dbObj->update($this->tableName, $dataArr, "AND ".$field." = '".$this->dbObj->escapeString($value)."' ".$where);
        if ($result) {
            return true;
        } else {
            $this->errorArr = array('code'=>10105, 'message'=>$this->message[10105]);
            return false;
        }
    }

    /**
     * 添加数据
     * @param string $tableName, 表名;
     * @param array $dataArr, 用户信息数组;
     * @return boolean;
     * @example obj->insert('tableName', array('id' => '1', 'title' => 'title', 'content' => 'content'));
     **/
    public function insert($dataArr)
    {
        if ($this->tableName == ''){
          $this->errorArr = array('code'=>10100, 'message'=>$this->message[10100]);
          return fasle;
        }
        $result = $this->dbObj->insert($this->tableName, $dataArr);
        if ($result) {
            return true;
        } else {
            $this->errorArr = array('code'=>10104, 'message'=>$this->message[10104]);
            return false;
        }
    }

    // 读取数据
    public function get($key, $value, $isMulti=false, $returnKey='*')
    {
        if ($this->tableName == ''){
          $this->errorArr = array('code'=>10100, 'message'=>$this->message[10100]);
          return fasle;
        }
        if ($key && $value) {
            $sql = "SELECT ".$returnKey." FROM `".$this->tableName."` WHERE 1 AND `".$key."` = '".$this->dbObj->escapeString($value)."'";
        } else {
            $sql = "SELECT ".$returnKey." FROM `".$this->tableName."` WHERE 1";
        }
        $result = $this->dbObj->get($sql, $isMulti);
        if (is_array($result)) {
            return $result;
        } else {
            $this->errorArr = array('code' => 10101, 'message' => $this->message[10101]);
            return false;
        }
    }

    /**
     * 获取数据列表与分页信息
     * @param string $where, 获取列表的查询条件;
     * @param array $orderArr, $orderArr[0] 需要排序的字段, $orderArr[1] 升降序;
     * @param int $limit, 每页显示的行数;
     * @param int $page, 当前页码;
     * @param string $reKey,SQL返回的列, 默认为所有;
     * @return array | boolean, 数组 $result['list'] 为数据列表, $result['pagination'] 分页信息;
     * @example obj->getList('AND id=1', array('id', 'desc'), 10, 1, 'id, datetime');
     **/
    final public function getList($where='', $orderArr=array('id','desc'), $limit=10, $page=1, $reKey='*')
    {
        if ($this->tableName == ''){
          $this->errorArr = array('code'=>10100, 'message'=>$this->message[10100]);
          return fasle;
        }
        // 检查排序规则
        if (is_array($orderArr)) {
            $order = "ORDER BY ".$orderArr[0]." ".$orderArr[1];
        }
        // 检查页码
        if (!is_numeric($page) || $page < 1) {
            $page = 1;
        }
        // 检查每页显示条数
        if (is_numeric($limit)) {
            $limitSql = "LIMIT ".($page-1)*$limit.",".$limit;
        }
        // 获取总行数
        $sql = "SELECT COUNT(*) AS totalRow FROM `".$this->tableName."` WHERE 1 ".$where;
        $result = $this->dbObj->get($sql);
        // 处理分页
        $result['pagination'] = $this->_getPagination($result['totalRow'], $limit, $page);
        // 加速查询
        $speedUpWhere = '';
        // 获取数据,此处涉及到需要读取列表的地方较多,如无指定返回指定列则使用 "SELECT *" 返回所有列.
        $sql = "SELECT ".$reKey." FROM `".$this->tableName."` WHERE 1 ".$speedUpWhere." ".$where." ".$order." ".$limitSql;
        $result['list'] = $this->dbObj->get($sql, 1);
        if (is_array($result)) {
            return $result;
        } else {
            $this->errorArr = array('code'=>10102, 'message'=>$this->message[10102]);
            return false;
        }
    }

    /**
     * 删除数据
     * @param string $where, 更多删除条件;
     * @param array $orderArr, $orderArr[0] 需要排序的字段, $orderArr[1] 升降序;
     * @param int $limit, 每页显示的行数;
     * @param int $page, 当前页码;
     * @param string $reKey,SQL返回的列, 默认为所有;
     * @return array | boolean, 数组 $result['list'] 为数据列表, $result['pagination'] 分页信息;
     * @example obj->getList('AND id=1', array('id', 'desc'), 10, 1, 'id, datetime');
     **/
    public function delete($field, $value, $where=''){
      if ($this->tableName == ''){
        $this->errorArr = array('code'=>10100, 'message'=>$this->message[10100]);
        return fasle;
      }
      $sql = "DELETE FROM `".$this->tableName."` WHERE `".$field."` = '".$value."' ".$where;
      $result = $this->dbObj->delete($sql);
      if ($result){
      	return true;
      } else {
        $this->errorArr = array('code'=>10106, 'message'=>$this->message[10106]);
      	return false;
      }
    }

    public function deleteAll(){
      if ($this->tableName == ''){
        $this->errorArr = array('code'=>10100, 'message'=>$this->message[10100]);
        return fasle;
      }
      $sql = "DELETE FROM `".$this->tableName."` WHERE 1";
      $result = $this->dbObj->delete($sql);
      if ($result){
      	return true;
      } else {
        $this->errorArr = array('code'=>10106, 'message'=>$this->message[10106]);
      	return false;
      }
    }

    // 生成翻译列表
    public function download()
    {
      if ($this->tableName == ''){
        $this->errorArr = array('code'=>10100, 'message'=>$this->message[10100]);
        return fasle;
      }
      $result = $this->get('page', '', true);
      foreach ($result as $key => $value) {
          foreach ($value as $keys => $values) {
              $languageArr[$key][$keys] = htmlspecialchars_decode($values, ENT_QUOTES);
          }
      }
      if (!$languageArr) {
          $languageArr[0] = array();
      }
      $content = json_encode($languageArr);
      ob_clean();
      header('HTTP/1.1 200 OK');
      header("Cache-Control: public");
      header("Pragma: cache");
      header('Content-Encoding: none');
      header('Content-Disposition: attachment; filename=language.json.txt');
      header('Content-Type: application/txt');
      header('Etag: '.md5($content));
      header('Content-Length: '.mb_substr($content));
      header("Cache-Control: max-age=2592000");
      exit($content);
    }

    /**
     * 处理分页显示页码
     * @param int $page, 当前页码;
     * @param int $limit, 每页显示行数;
     * @param int $totalRow, 总行数;
     * @return array;
     * @example obj->_getPagination(50, 10, 1);
     **/
    private function _getPagination($totalRow, $limit, $page)
    {
        // 总页数
        $totalPage = ceil($totalRow/$limit);
        // 上一页页码
        $previous = ($page-1) > 0 ? $page-1 : 1;
        // 下一页页码
        $next = ($page+1) <= $totalPage ? $page+1 : $totalPage;
        // 页码范围
        if ($totalPage > 10) {
            if ($page < 6) {
                $begin = 1;
                $end = 10;
            } else {
                $begin = ($page-5) > 0 ? $page-5 : 1;
                if (($page+5) > $totalPage) {
                    $begin = $totalPage-9;
                    $end = $totalPage;
                } else {
                    $end = $begin+9;
                }
            }
        } else {
            $begin = 1;
            $end = $totalPage != '0' ? $totalPage : '1';
        }
        return array('totalRow'=>$totalRow, 'totalPage'=>$totalPage, 'page'=>$page, 'previous'=>$previous, 'next'=>$next, 'begin'=>$begin, 'end'=>$end);
    }
}
